<?php

namespace App\Http\Controllers\Backend;

use App\Http\Requests\Backend\EditSchool;
use App\Http\Requests\Backend\StoreSchool;
use App\Http\Resources\Backend\SchoolResource;
use App\Models\AdminLog;
use App\Models\School;
use App\Services\SchoolService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * Class SchoolController
 * @package App\Http\Controllers\Backend
 * 学校
 */
class SchoolController extends BackendController
{
    /**
     * @param Request $request
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     * 学校列表
     */
    public function index(Request $request)
    {
        $schools = School::orderBy('created_at', 'desc')
            ->with('rule')
            ->nameLike($request->name)
            ->paginate($request->size);
        return SchoolResource::collection($schools);
    }

    /**
     * @param StoreSchool $request
     * @return SchoolResource|array
     * @throws \Exception
     * 新增学校信息
     */
    public function store(StoreSchool $request)
    {
        DB::beginTransaction();
        try {
            $school = SchoolService::add($request);
            AdminLog::log('新增学校' . $school->name);
            DB::commit();
            return new SchoolResource($school);
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->fail($exception->getMessage());
        }
    }

    /**
     * @param EditSchool $request
     * @param School $school
     * @return SchoolResource
     * 编辑学校信息
     */
    public function update(EditSchool $request, School $school)
    {
        $school = SchoolService::edit($school);
        AdminLog::log('编辑学校' . $school->name);
        return new SchoolResource($school);
    }
}
